<template>
  <div>
    <!-- 搜索页面头部 -->
    <div class="search-header">
      <!-- 后退按钮 -->
      <van-icon
        name="arrow-left"
        color="white"
        size="0.48rem"
        class="goback"
        @click="$router.back()"
      />
      <!-- 搜索组件 -->
      <van-search
        placeholder="请输入搜索关键词"
        background="#007BFF"
        shape="round"
        v-model="kw"
        @input="searchFn"
        ref="search"
        @search="toResultFn"
      />
    </div>
    <!-- 联想菜单 -->
   <div v-if="list.length>0">
     <van-cell v-for="(item, index) in list" :key="index" @click="toResultFn(kw)">
      <template #default>
        <span v-html="item"></span>
      </template>
    </van-cell>
   </div>
    <!-- 搜索历史 -->
    <div class="search-history" v-else>
      <!-- 标题 -->
      <van-cell title="搜索历史">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="delete" class="search-icon" @click="clearListFn"/>
        </template>
      </van-cell>
      <!-- 历史列表 -->
      <div class="history-list">
        <span class="history-item" v-for="(item, index) in history" :key="index" @click="toResultFn(item)" >{{item}}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { getSuggestion } from '@/api'
export default {
  name: 'SearchVue',
  data () {
    return {
      kw: '', // 搜索关键字
      timer: '',
      list: [], // 联想列表
      history: JSON.parse(localStorage.getItem('historyKw')) || []
    }
  },
  methods: {
    // 用户搜索，返回联想菜单
    searchFn () {
      // 防抖
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        if (this.kw.trim()) {
          const res = await getSuggestion(this.kw)
          this.list = res.data.data.options
          // 关键字高亮
          if (this.list[0]) {
            const reg = new RegExp(this.kw, 'ig') // 规则 - 不分大小写，全局查找
            this.list = this.list.map((item) => {
              return item.replace(reg, (watch) => {
                return `<span style='color:red'>${watch}</span>`
              })
            })
          }
        } else {
          this.list = ''
        }
      }, 500)
    },

    // 去结果页 并且保存搜索记录
    toResultFn (item = this.kw) {
      if (this.kw.trim()) {
        // 添加到历史列表
        this.history.push(this.kw)
        // 去重
        this.history = Array.from(new Set(this.history))
        // 历史记录保存到本地
        localStorage.setItem('historyKw', JSON.stringify(this.history))
      }
      // to详细页
      this.$router.push(`/searchResult/${item}`)
    },

    // 清空历史记录
    clearListFn () {
      this.history = []
      localStorage.removeItem('historyKw')
    }
  },
  mounted () {
    this.$refs.search.querySelector('input').focus()
  }
}
</script>

<style scoped lang="less">
.search-header {
  height: 46px;
  display: flex;
  align-items: center;
  background-color: #007bff;
  overflow: hidden;
  /*后退按钮*/
  .goback {
    padding-left: 14px;
  }
  /*搜索组件*/
  .van-search {
    flex: 1;
  }
}
.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
</style>
